package cxy.highConcurrency;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockDemo_2 {
	private Object data;
	
	private volatile boolean cacheValid;
	
	private final ReadWriteLock rwl = new ReentrantReadWriteLock();
	
	// 读锁 
	final Lock r = rwl.readLock(); 
	
	//写锁
	final Lock w = rwl.writeLock();
	
	void processCachedData() {
		//获取读锁
		r.lock();
		if (!cacheValid) {
			//释放读锁，因为不允许读锁升级
			r.unlock();
			//获取写锁
			w.lock();
			try {
				if (!cacheValid) {
					//获取数据
					//data =
					cacheValid = true;
				}
				//释放写锁前，降级为读锁
				r.lock();
			} finally {
				w.unlock();
			}
			
			//此处仍然持有读锁
			try {
				//使用数据
				
			} finally {
				r.unlock();
			}
			
		}
		
	}
	
	
}
